<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use Exception;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 费改申请
 *
 * @icon fa fa-circle-o
 */
class EquipRateModsApply extends Backend
{

    /**
     * EquipRateModsApply模型对象
     * @var \app\admin\model\EquipRateModsApply
     */
    protected $model = null;

    protected $tempModel = null;
    protected $proModel = null;
    protected $userModel = null;
    protected $rateModel = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\EquipRateModsApply;
        $this->proModel = new \app\common\model\Product;
        $this->userModel = new \app\common\model\User;
        $this->rateModel = new \app\common\model\EquipRate;
        $this->tempModel = new \app\admin\model\EquipRateTplt;
        $this->view->assign("isApplyList", $this->model->getIsApplyList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        $list = [];
        $params = $this->request->param("filter");
        $selectParams = json_decode($params, true);
        $ex = explode(" - ", $selectParams["create_time"]);
        $where = "(create_time >= " . strtotime($ex[0]) . " and create_time <= " . strtotime($ex[1]) . ")";
        if (isset($selectParams["sn"])) {
            $where .= " and sn = '" . $selectParams["sn"] . "'";
        }
        if (isset($selectParams["is_apply"])) {
            $where .= " and is_apply = " . $selectParams["is_apply"];
        }
        $limit = $this->request->param("limit");
        $offset = $this->request->param("offset");
        $count = $this->model->where($where)->count();
        if ($count) {
            $field = "*,";
            $field .= "case is_take when 0 then  '未审' when 1 then 'T+0' when 2 then 'D+1' when 3 then '立即生效' end takes,";
            $field .= "case apply_typs when 'D' then  '默认' when 'T' then '调价' end  typs";
            $list = $this->model->where($where)->field($field)->limit($offset, $limit)->select();
            if ($list) {
                $pro = $this->proModel->column("name", "id");
                foreach ($list as $key => $val) {
                    $list[$key]["user"] = $this->userModel->where("id=" . $val["agid"])->value("nickname");
                    $list[$key]["pros"] = $pro[$val["pro_id"]];
                }
            }
        }
        $result = ['total' => $count, 'rows' => $list];
        return json($result);
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $pro_arr = $this->proModel->field("id,name")->select();
            $row->user = $this->userModel->where("id=" . $row->agid)->value("nickname");
            $row->typs = ($row->apply_typs == 'D' ? '默认' : '调价');
            $row->is_take = $this->tempModel->where("pro_id = " . $row->pro_id . " and typs = '" . $row->apply_typs . "'")->value("is_take");
            $this->assign("proArr", $pro_arr);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            $reg = Config("msg");
            $data = $params["row"];
            $find = $this->model
                ->where("id=" . $ids)
                ->find();
            if ($find->is_apply == $data["is_apply"]) {
                throw new \Exception($reg["0303"]);
            } else {
                if ($find->is_apply == 1 || $find->is_apply == 3) {
                    throw new \Exception($reg["0304"]);
                } else {
                    $phone = session("admin.mobile");
                    $nickname = session("admin.username");
                    $update =  [
                        "is_apply"      => $data["is_apply"],
                        "status"        => $data["status"],
                        "apply_time"    => time(),
                        "is_take"       => $data["is_take"],
                        "appyPhone"     => (empty($phone) ?  $nickname : $phone)
                    ];
                    $ret = $this->model->where("id=" . $ids)->update($update);
                    if ($ret) {
                        $flag = true;
                        if ($update["is_apply"] == 1 && $update["status"] == 1) {
                            if ($update["is_take"] == 3) {
                                $upRes = \app\times\controller\oprate\Feemods::instance()->handle($ids);
                                if ($upRes === false) $flag = false;
                            } else {
                                $times = strtotime(date("Y-m-d", time()));
                                if ($update["is_take"] == 2) {
                                    $times = strtotime("+1 day", strtotime(date("Y-m-d", $update["apply_time"])));
                                }
                                $arrs = ["ids" => $ids, "times" => $times];
                                $id = \app\common\func\Tables::instance()->general_storage("equip_rate_mods_times", $arrs, "费改定时临时表");
                                if (!$id) {
                                    $flag = false;
                                }
                            }
                        }
                        if ($flag) {
                            Db::commit();
                            $result = true;
                        }
                    }
                }
            }
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success($reg["0300"]);
    }
}
